package com.lagou.blog.controller;

import com.lagou.blog.model.BlogPageInfo;
import com.lagou.blog.service.BlogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;

/**
 * 博客视图控制器
 */
@Controller
public class BlogController {
    /**
     * 博客服务
     */
    @Autowired
    private BlogService blogService;

    /**
     * 获取博客文章信息
     *
     * @return 博客文章信息
     */
    @RequestMapping("/index")
    public ModelAndView showBlogs() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("index");

        Map<String, Object> model = modelAndView.getModel();
        BlogPageInfo blogPageInfo = blogService.queryBlogs(1, 2);

        model.put("blogPageInfo", blogPageInfo);
        return modelAndView;
    }

    /**
     * 获取上一个页号
     *
     * @param currentPage 当前页号
     * @return 上一个页号
     */
    private int getPrevPage(Integer currentPage) {
        if ((currentPage == null) || (currentPage <= 1)) {
            return 1;
        }

        int page = currentPage - 1;
        return page;
    }

    /**
     * 获取下一个页号
     *
     * @param currentPage 当前页号
     * @return 下一个页号
     */
    private int getNextPage(Integer currentPage, Integer totalPage) {
        if ((currentPage == null) || (totalPage == null)) {
            return 1;
        }

        if (currentPage >= totalPage) {
            return currentPage;
        }

        int page = currentPage + 1;
        return page;
    }

    /**
     * 获取博客文章信息
     *
     * @param currentPage 当前页号
     * @return 博客文章信息
     */
    @RequestMapping("/blogs/prev")
    public ModelAndView showPrevBlogs(Integer currentPage) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("index");

        Map<String, Object> model = modelAndView.getModel();
        BlogPageInfo blogPageInfo = blogService.queryBlogs(getPrevPage(currentPage), 2);

        model.put("blogPageInfo", blogPageInfo);
        return modelAndView;
    }

    /**
     * 获取博客文章信息
     *
     * @param currentPage 当前页号
     * @return 博客文章信息
     */
    @RequestMapping("/blogs/next")
    public ModelAndView showNextBlogs(Integer currentPage, Integer totalPage) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("index");

        Map<String, Object> model = modelAndView.getModel();
        BlogPageInfo blogPageInfo = blogService.queryBlogs(getNextPage(currentPage, totalPage), 2);

        model.put("blogPageInfo", blogPageInfo);
        return modelAndView;
    }
}
